import { ArrowsAltOutlined, ExpandAltOutlined, SyncOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import React, { useEffect, useState } from 'react';
import '@amap/amap-jsapi-types';
import AMapLoader from '@amap/amap-jsapi-loader';

interface XAMapProps {
  container: string;
  options?: AMap.MapOptions;
  width: string | number;
  height: string | number;

  apiLoaderOptions: {
    key: string;
    version?: string;
  };

  children?: any;
  refresh?: () => Promise<void>;
  coordinateListener?: (data: { lng: number; lat: number }) => void;
}

const XAMap: React.FC<XAMapProps> = (props) => {
  const {
    container,
    options,
    width,
    height,

    apiLoaderOptions: { key, version = '1.4.15' },

    children,
    refresh,
    coordinateListener,
  } = props;

  const [mapLoaded, setMapLoaded] = useState<boolean>(false);
  const [map, setMap] = useState<AMap.Map>();
  const [loadingRefresh, setLoadingRefresh] = useState<boolean>(false);

  const [expand, setExpand] = useState<boolean>(false);

  useEffect(() => {
    AMapLoader.load({ key, version, AMapUI: { version: '1.1' } }).then(() => {
      if (!map) {
        const xmap = new AMap.Map(container, options);

        if (coordinateListener) {
          xmap.on('click', (e) => coordinateListener(e.lnglat));
        }

        setMap(xmap);
      }
      if (!mapLoaded) setMapLoaded(true);
    });
  }, []);

  return (
    <div
      id={container}
      style={{
        ...(expand
          ? { position: 'fixed', left: 0, top: 0, height: '100%', width: '100%', zIndex: 50 }
          : { height, width }),
      }}
    >
      {mapLoaded && (
        <Button
          shape="circle"
          icon={expand ? <ArrowsAltOutlined /> : <ExpandAltOutlined />}
          onClick={() => setExpand(!expand)}
          style={{ position: 'absolute', top: 30, right: 30, zIndex: 50 }}
        />
      )}
      {mapLoaded && refresh && (
        <Button
          shape="circle"
          icon={<SyncOutlined spin={loadingRefresh} />}
          onClick={() => {
            if (refresh) {
              setLoadingRefresh(true);
              refresh().finally(() => {
                setLoadingRefresh(false);
              });
            }
          }}
          style={{ position: 'absolute', top: 70, right: 30, zIndex: 50 }}
        />
      )}
      {mapLoaded && map
        ? React.Children.map(children, (child) => React.cloneElement(child, { __map__: map }))
        : null}
    </div>
  );
};

export default XAMap;
